package com.lazyframework.commons.support;

import com.github.pagehelper.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 用于在Service层把Entity转换为Model
 * <p>
 * 泛型E：Entity实体
 * </p>
 * <p>
 * 泛型M：Model对象
 * </p>
 * Create by lazy in 2019/10/11
 * <p>
 * Update by lazy in 2020/07/22. 移除对于Page对象的转换，减少对于第三方库的依赖。
 */
public interface Convertible {

    Logger log = LoggerFactory.getLogger(Convertible.class);

    /**
     * 这没什么好注释的，如果看不懂买豆腐撞了吧^_^
     *
     * @param source
     * @param clazz
     * @return
     */
    default <M> M convert(Object source, Class<M> clazz, String... ignoreProperties) {
        if (source == null) {
            return null;
        }
        M target;
        try {
            target = clazz.newInstance();
            StrongerBeanUtils.copyProperties(source, target, ignoreProperties);
        } catch (InstantiationException | IllegalAccessException e) {
            log.error("{} is not a standard JavaBean.", clazz.getName(), e);
            return null;
        }
        return target;
    }

    /**
     * 这没什么好注释的，如果看不懂买豆腐撞了吧^_^
     *
     * @param sources
     * @param clazz
     * @return
     */
    default <M> Collection<M> convert(Collection<?> sources, Class<M> clazz, String... ignoreProperties) {
        Collection<M> models = new ArrayList<>();
        sources.forEach(source -> models.add(convert(source, clazz, ignoreProperties)));
        return models;
    }

    /**
     * 移除对于PageHelper依赖
     * 这没什么好注释的，如果看不懂买豆腐撞了吧^_^
     *
     * @param page
     * @param clazz
     * @return
     */
    default <M> PageInfo<M> convert(Page<?> page, Class<M> clazz, String... ignoreProperties) {
        PageInfo<M> pageInfo = new PageInfo<>();
        pageInfo.setSize(page.getPageSize());
        pageInfo.setPage(page.getPageNum());
        pageInfo.setTotalPage(page.getPages());
        pageInfo.setTotalElements((int) page.getTotal());
        pageInfo.setContent(convert(page.getResult(), clazz, ignoreProperties));
        return pageInfo;
    }

}
